import 'package:flutter/material.dart';
import 'package:flutter_community/pages/home/index.dart';
import 'package:flutter_community/pages/mine/index.dart';
import 'package:flutter_community/utils/eventBus.dart';
import 'package:flutter_community/utils/preference.dart';

class MyTabBar extends StatefulWidget {
  const MyTabBar({super.key});

  @override
  State<MyTabBar> createState() => _MyTabBarState();
}

class _MyTabBarState extends State<MyTabBar>
    with SingleTickerProviderStateMixin {
  //定义当前索引
  int _currentIndex = 0;
  late TabController _tabController;

  @override
  void initState() {
    super.initState();

    // 创建与Tab数量对应的控制器
    _tabController = TabController(length: 2, vsync: this);
    // 添加状态变化监听
    _tabController.addListener(_handleTabSelection);

    //初始化token
    Future.delayed(Duration.zero, () async {
      await TokenManager().initToken();
      // print('获取token${TokenManager().getToken()}');
    });
    //接收event指令
    eventBus.on<LogoutEvent>().listen((event) {
      Navigator.pushNamed(context, '/login');
    });
  }

  // 处理Tab选择变化
  void _handleTabSelection() {
    if (_tabController.indexIsChanging) {
      setState(() {
        _currentIndex = _tabController.index;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: TabBarView(
          controller: _tabController,
          //禁止左右滑动
          physics: const NeverScrollableScrollPhysics(),
          children: [
            const HomePage(),
            MinePage(
              currentIndex: _currentIndex,
            )
          ]),
      bottomNavigationBar: TabBar(
        controller: _tabController,
        labelColor: const Color.fromARGB(255, 186, 217, 246),
        unselectedLabelColor: Colors.black,
        //选中之后icon的颜色
        tabs: [
          Tab(
              icon: Image.asset(
                _currentIndex == 0
                    ? 'assets/tabs/home_active.png'
                    : 'assets/tabs/home_default.png',
                width: 24,
                height: 24,
              ),
              text: '首页'),
          Tab(
              icon: Image.asset(
                _currentIndex == 1
                    ? 'assets/tabs/my_active.png'
                    : 'assets/tabs/my_default.png',
                width: 24,
                height: 24,
              ),
              text: '我的'),
        ],
        indicatorColor: Colors.transparent, // 隐藏指示器
      ),
      // );
      // );
    );
  }
}
